#!/usr/bin/env bash

set -eu

source $SNAP/actions/common/utils.sh

use_snap_env

if [ -e ${SNAP_DATA}/var/lock/clustered.lock ]
then
  echo "This MicroK8s deployment is acting as a node in a cluster. Please use the microk8s add-node on the master."
  exit 1
fi

if echo "$*" | grep -q -- 'help'; then
  # Call add_token.py help
  ${SNAP}/usr/bin/python3 ${SNAP}/scripts/wrappers/add_token.py --help
  exit 0
fi

exit_if_not_root

exit_if_no_permissions

subject=$("${SNAP}/openssl.wrapper" x509 -sha256 -days 365 -noout -subject -in "$SNAP_DATA/certs/ca.crt")
if [[ $subject == *"127.0.0.1"* ]]; then
  echo "Clustering requires a fresh MicroK8s installation. Reinstall with:"
  echo "sudo snap remove microk8s"
  install_message="sudo snap install microk8s"
  if ! is_strict
  then
    install_message="${install_message} --classic"
  fi
  echo "$install_message"
  exit 1
fi

exit_if_stopped

if [ ! -f "$SNAP_DATA/credentials/cluster-tokens.txt" ]; then
  touch $SNAP_DATA/credentials/cluster-tokens.txt
fi

group=$(get_microk8s_or_cis_group)

if getent group ${group} >/dev/null 2>&1
then
  chgrp ${group} $SNAP_DATA/credentials/cluster-tokens.txt >/dev/null 2>&1 || true
  chmod ug+rw $SNAP_DATA/credentials/cluster-tokens.txt >/dev/null 2>&1 || true
  chmod o-rwX $SNAP_DATA/credentials/cluster-tokens.txt >/dev/null 2>&1 || true
fi

# Use python's built-in (3.6+) secrets generator to produce the token.
${SNAP}/usr/bin/python3 ${SNAP}/scripts/wrappers/add_token.py "${@}"
